<?php

declare(strict_types=1);

namespace app\model;

use app\model\base\BaseCouponConfigModel;
use think\facade\Cache;
use think\model\concern\SoftDelete;

/**
 * 
 *
 * @mixin \think\Model
 * @property int $id
 * @property int $agent_id 代理id
 * @property int $quote_id 引用id,权益商品id
 * @property string $value 溢价比例
 * @property bool $status 状态(0未启用 1启用)
 * @property bool $config_type 针对单个商品  1 全局   2 平台代理设置  3 代理本身
 * @property bool $global 全局设置      1 全局   2 平台代理设置  3.代理本身
 * @property string $created_at 创建时间
 * @property string $updated_at 更新时间
 * @property string $deleted_at 删除时间
 * @property int $old_quote_id 旧的quote_id
 * @method static \think\db\Query onlyTrashed()
 * @method static \think\db\Query withTrashed()
 */
class CouponConfig extends BaseCouponConfigModel
{
    use SoftDelete;

    const STATUS_ACTIVE = 1; //激活
    const STATUS_CLOSE = 0; //关闭

    //针对全局的溢价设置
    const GLOBAL_PTQJ = 1;    //平台全局
    const GLOBAL_PTDLQJ = 2;  //平台某个代理全局
    const GLOBAL_DLQJ = 3;    //代理全局

    //针对单个商品的溢价设置
    const CONFIG_TYPE_PTDG = 1;    //平台单个商品
    const CONFIG_TYPE_PTDLDG = 2;  //平台代理单个商品
    const CONFIG_TYPE_DLDG = 3;    //代理某个商品

    //溢价类型
    const PREMIUM_TYPE_QJ = 1;     //全局溢价
    const PREMIUM_TYPE_DG = 2;     //单个溢价

    const COUPONCONFIG_FINDCONFIGBYPARAMS_TAG = 'CouponConfig_findConfigByParams_tag';
    const COUPONCONFIG_CACHE_ONE = 'couponconfig_cache_one';
    const COUPONCONFIG_CACHE_SELECT_BY_AGENTID = 'couponconfig_cache_select_by_agentid';
    /**
     * 溢价管理----根据条件查询溢价数据（后台使用）
     * @access public
     * @return array
     */
    public function findConfigByParams($map)
    {
        $cacheTag = self::COUPONCONFIG_FINDCONFIGBYPARAMS_TAG;
        $cacheKey = 'CouponConfig_findConfigByParams_cache'.json_encode($map);
        $cacheRes = Cache::get($cacheKey);
        if ($cacheRes) {
            return $cacheRes;
        }
        $res = self::where($map)
            ->field('id, agent_id, quote_id, value as premium_rate, config_type, global,updated_at,created_at')
            ->find();
        Cache::tag($cacheTag)->set($cacheKey, $res, 3600*24*1);
        return $res;

    }

    /**
     * 溢价管理----根据条件查询溢价数据（下单使用）
     * @access public
     * @param int $channel_id 产品id
     * @param int $agent_id   代理id
     * @return array
     */
    public function getPremiumRate(int $channel_id, int $agent_id)
    {
        //平台和代理的溢价比例
        $premium_rate = array();
        $couponConfig = CouponConfig::query()
            ->where('agent_id', $agent_id)
            ->cache(CouponConfig::COUPONCONFIG_CACHE_SELECT_BY_AGENTID.$agent_id,1)
            ->where('status', CouponConfig::STATUS_ACTIVE)->select();
        $query = collect($couponConfig);
        $platform = $this->queryPlatformPremiumRate($query, $channel_id, $agent_id);
        $agent = $this->queryAgentPremiumRate($query, $channel_id);
        $premium_rate['platform'] = $platform;
        $premium_rate['agent'] = $agent;
        return $premium_rate;
    }

    //查询平台端溢价比例
    protected function queryPlatformPremiumRate($query, $channel_id, $agent_id)
    {
//        $query->cache(CouponConfig::COUPONCONFIG_CACHE_ONE.$channel_id.$agent_id);


        $quote_id = CouponProductChannel::query()->where('id',$channel_id)->value('product_id',0);



        //默认溢价比例
        $default_premium_rate = 0;
        if ($agent_id == 0) { //平台后台
            //1.查询具体产品是否设置有溢价比例
            $platform_type_ptdl = $this->getPremiumValue(['quote_id' => $quote_id, 'config_type' => self::CONFIG_TYPE_PTDG]);
            //2.查询全局溢价比例
            if (empty($platform_type_ptdl)) {

                //4.查询平台是否设置了全局溢价比例
                $platform_global_ptqj = $this->getPremiumValue(['global' => self::GLOBAL_PTQJ]);

            }
            if (isset($platform_type_ptdl) && $platform_type_ptdl) {

                $platform = $platform_type_ptdl;

            } else if(isset($platform_global_ptqj) && $platform_global_ptqj) {

                $platform = $platform_global_ptqj;

            }  else {
                $platform = $default_premium_rate;
            }
        } else {
            //一.查询平台为某个产品设置的溢价比例
            //0.查询平台具体某个代理使用的模板类型  0-模板  1-自定义
            $mould = AgentConfig::where('agent_id', $agent_id)->cache(AgentConfig::ONE_CACHE_KEY.$agent_id,1)->value('mould');
            //1.查询平台是否为具体某个产品设置溢价
            if ($mould  == AgentConfig::MOULD_ZDY) { //自定义模板;

                $platform_config_type_ptdldg = $query->where('quote_id', $quote_id)->where('config_type', self::CONFIG_TYPE_PTDLDG)->first();

                if ($platform_config_type_ptdldg) { //存在

                    $platform_type_ptdldg = $platform_config_type_ptdldg->value;//value1

                } else {  //不存在

                    //2.查询平台是否为具体某个平台设置全局溢价比例
                    $platform_config_global_ptdlqj = $query->where('global', self::GLOBAL_PTDLQJ)->first();

                    if ($platform_config_global_ptdlqj) {

                        $platform_global_ptdlqj = $platform_config_global_ptdlqj->value; //value2

                    }
                }
            } else { //默认模板
                $platform_type_ptdldg = $platform_global_ptdlqj = $default_premium_rate;
            }
            if (empty($platform_global_ptdlqj)) { //value2
                //3.查询平台是否为某个产品设置溢价比例

                $platform_type_ptdg = $this->getPremiumValue(['quote_id' => $channel_id, 'config_type' => self::CONFIG_TYPE_PTDG]);//value3

                if (empty($platform_type_ptdg)) {

                    //4.查询平台是否设置了全局溢价比例
                    $platform_global_ptqj = $this->getPremiumValue(['global' => self::GLOBAL_PTQJ]);//value4

                }
            }
            if (isset($platform_type_ptdldg) && $platform_type_ptdldg) {

                $platform = $platform_type_ptdldg;

            } else if(isset($platform_global_ptdlqj) && $platform_global_ptdlqj) {

                $platform = $platform_global_ptdlqj;

            } else if(isset($platform_type_ptdg) && $platform_type_ptdg) {

                $platform = $platform_type_ptdg;

            } else if(isset($platform_global_ptqj) && $platform_global_ptqj) {

                $platform = $platform_global_ptqj;

            } else {

                $platform = $default_premium_rate;

            }
        }
        return $platform;
    }


    //查询代理端溢价比例
    protected function queryAgentPremiumRate($query, $channel_id)
    {
        //默认溢价比例
        $default_premium_rate = 0;
        //二.查询代理端自己设置的溢价比例
        //1.查询代理端是否为单独某个产品设置溢价比例
        $agent_config_type_dldg = $query->where('quote_id', $channel_id)->where('config_type', self::CONFIG_TYPE_DLDG)->first();
        if ($agent_config_type_dldg) {
            $agent_type_dldg = $agent_config_type_dldg->value;
        } else {
            //查询代理端的全局溢价比例
            $agent_config_global_dlqj = $query->where('global', self::GLOBAL_DLQJ)->first();
            if ($agent_config_global_dlqj) {
                $agent_global_dlqj = $agent_config_global_dlqj->value;
            }
        }
        if (isset($agent_type_dldg) && $agent_type_dldg) {

            $agent = $agent_type_dldg;

        } else if(isset($agent_global_dlqj) && $agent_global_dlqj) {

            $agent = $agent_global_dlqj;

        } else {

            $agent = $default_premium_rate;

        }
        return $agent;
    }


    //根据条件返回溢价比例
    protected function getPremiumValue($map)
    {
        return self::where($map)->where('status', CouponConfig::STATUS_ACTIVE)->value('value');
    }

}

